﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SDL
{
    // TODO: content must be able to be viewed in the designer... how?

    // A view contained by a tab group.
    [TemplatePartAttribute(Name = "PART_Header", Type = typeof(FrameworkElement))]
    public class TabView : TabItem, IViewElement
    {
        /////////////////////////////////////////////////////////////////////////////
        // Default Constructor

        public TabView()
        {
            Header = "TAB ITEM " + _uniqueID++;

            Loaded += new RoutedEventHandler(TabView_Loaded);
            Unloaded += new RoutedEventHandler(TabView_Unloaded);
        }

        /////////////////////////////////////////////////////////////////////////////
        // IElement

        public FrameworkElement AsFrameworkElement()
        {
            return this;
        }

        /////////////////////////////////////////////////////////////////////////////
        // Event Handlers

        private void TabView_Loaded(object sender, RoutedEventArgs e)
        {
            _container = Parent as IViewContainer;
        }

        private void TabView_Unloaded(object sender, RoutedEventArgs e)
        {
            _container = null;
        }

        private void TabHeader_StartDrag(object sender, MouseButtonEventArgs e)
        {
            _container.StartDrag(this);
        }

        /////////////////////////////////////////////////////////////////////////////
        // Private Data

        private static int _uniqueID = 0;
        private IViewContainer _container;
        private FrameworkElement _header;

        /////////////////////////////////////////////////////////////////////////////
        // Control

        static TabView()
        {
            DefaultStyleKeyProperty.OverrideMetadata(
                typeof(TabView),
                new FrameworkPropertyMetadata(typeof(TabView)));
        }

        public override void OnApplyTemplate()
        {
            // find the header
            _header = GetTemplateChild("PART_Header") as FrameworkElement;
            if( _header != null )
            {
                _header.MouseLeftButtonDown +=
                    new MouseButtonEventHandler(TabHeader_StartDrag);
            }
        }
    }
}
